import React, { Fragment, useEffect, useRef } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import { Form, Input, Button, Table, DatePicker } from 'antd';
import { eventTrack } from '@/utils/track';
// import { QuickForm, utils } from 'vv-frontend-components';
import { utils } from 'vv-frontend-components';
// import cookie from 'js-cookie';
// import { history } from 'umi';
// import Locale from '@/utils/locale';
import { CompanyDepartPlus } from '@/containers';
import { dateConversion2, download } from '@/utils/utils';
// import request from '@/utils/request';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { Pagination } from '@/components';
import styles from './index.less';

// const { locale } = new Locale('stat.overtime');
const { MonthPicker } = DatePicker;
// const { Option } = Select;
// const { TabPane } = Tabs;
const { deepTrim } = utils;

const List = ({ activeKey, form, overtime, loading, dispatch, location, route }) => {
    const {
        query: {
            // id,
            employeeName,
            companyId,
            departmentId,
            startTime,
            endTime
        } = {}
    } = location;
    const { getFieldsValue, getFieldDecorator } = form;
    const { monthPagination: pagination, monthList: data } = overtime;
    const { authCode } = new AuthCode(route.code);
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { firstCompanyCode, firstDepartmentCode } = user?.firstOrgInfo;
    const handleExport = () => {
        const { companyDepart, month, userNameForm } = getFieldsValue();

        download({
            getData: () =>
                dispatch({
                    type: 'attendRecord/fetchMonthExport',
                    payload: deepTrim({
                        companyCode: companyDepart?.companyId || '',
                        departmentCode: companyDepart?.departmentId || '',
                        month: month ? moment(month).format('YYYY-MM') : '',
                        userName: userNameForm || '',
                        status: ''
                    })
                })
        });
        // 埋点
        eventTrack({
            eventName: 'personnel_management_attendance_overtime_export_click',
            eventProps: {
                label: '出勤统计-导出',
                tabs: '月统计'
            }
        });
    };

    const columns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            key: 'userNo'
        },
        {
            title: '姓名',
            dataIndex: 'userName',
            key: 'userName'
        },
        {
            title: '组织机构',
            dataIndex: 'departName',
            key: 'departName'
        },
        {
            title: '加班总计',
            dataIndex: 'workOverAllTimeMinute',
            key: 'workOverAllTime'
        },
        {
            title: '工作日加班',
            dataIndex: 'workOverTimeMinute',
            key: 'workOverTime'
        },
        {
            title: '休息日加班',
            dataIndex: 'restTimeMinute',
            key: 'restTime'
        },
        {
            title: '节假日加班',
            dataIndex: 'holidayTimeMinute',
            key: 'holidayTime'
        },
        {
            title: '当月调休',
            dataIndex: 'nowMonthPaid',
            key: 'nowMonthPaid',
            render(text) {
                return dateConversion2(text);
            }
        }
    ];

    const fetchList = () => {
        const { companyDepart, month, userNameForm } = getFieldsValue();
        dispatch(
            deepTrim({
                type: 'overtime/fetchMonthList',
                payload: {
                    companyCode: companyDepart?.companyId || '',
                    departmentCode: companyDepart?.departmentId || '',
                    month: month ? moment(month).format('YYYY-MM') : '',
                    userName: userNameForm || '',
                    status: '',
                    pageNo: pagination.current,
                    pageSize: pagination.pageSize
                }
            })
        );
    };

    const handleSubmit = async e => {
        const { eType } = e;
        // e.preventDefault();
        if (overtime.monthPagination.current !== 1) {
            await dispatch({
                type: 'overtime/save',
                payload: {
                    monthPagination: {
                        ...overtime.monthPagination,
                        current: 1
                    }
                }
            });
        } else {
            fetchList();
        }
        eventTrack({
            eventName:
                eType === 'search'
                    ? 'personnel_management_attendance_overtime_search_click'
                    : 'personnel_management_attendance_overtime_reset_click',
            eventProps: {
                key_works: eType === 'search' ? JSON.stringify(form.getFieldsValue()) : null,
                tabs: '月统计'
            }
        });
    };

    const changeCurrent = async newPagination => {
        await dispatch({
            type: 'overtime/save',
            payload: {
                monthPagination: {
                    ...overtime.monthPagination,
                    ...newPagination
                }
            }
        });
    };

    const isFirstRun = useRef(true);
    useEffect(() => {
        form.setFieldsValue({
            userNameForm: employeeName,
            month: startTime && endTime ? moment(moment(startTime).format('YYYY-MM')) : moment()
        });
        // init();
        fetchList();
    }, []);
    useEffect(
        () => () => {
            isFirstRun.current = true;
        },
        []
    );
    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        // 第一次不运行
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        if (activeKey === '1') {
            fetchList();
        }
    }, [activeKey, pagination.pageSize, pagination.current, employeeName]);

    useEffect(
        () => () => {
            dispatch({
                type: 'overtime/save',
                payload: {
                    monthPagination: {
                        current: 1,
                        pageSize: 10
                    }
                }
            });
        },
        []
    );

    const initCompanyDepart = {
        companyId: companyId || firstCompanyCode,
        departmentId: departmentId || firstDepartmentCode
    };

    return (
        <Fragment>
            <Form
                layout="inline"
                style={{ marginBottom: 16 }}
                onSubmit={e => {
                    e.preventDefault();
                    handleSubmit({
                        eType: 'search'
                    });
                }}
            >
                <Form.Item label="机构" className={styles.temp}>
                    {getFieldDecorator('companyDepart', { initialValue: initCompanyDepart })(<CompanyDepartPlus />)}
                </Form.Item>
                <Form.Item label="员工">
                    {getFieldDecorator('userNameForm', {
                        initialValue: ''
                    })(<Input placeholder="输入姓名" allowClear />)}
                </Form.Item>
                <Form.Item label="考勤月">
                    {getFieldDecorator('month', {
                        initialValue: moment()
                    })(<MonthPicker allowClear={false} format="YYYY-MM" />)}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
                <Form.Item>
                    <AuthComponent code={authCode('export')}>
                        <Button onClick={handleExport} disabled={loading.effects['overtime/fetchMonthList']}>
                            导出
                        </Button>
                    </AuthComponent>
                </Form.Item>
            </Form>
            <Table
                bordered
                columns={columns}
                loading={loading.models.overtime}
                dataSource={data}
                rowKey="id"
                onChange={changeCurrent}
                pagination={false}
            />
            <Pagination onChange={changeCurrent} {...pagination} loading={loading.models.overtime} />
        </Fragment>
    );
};

export default connect(({ overtime, loading }) => ({
    overtime,
    loading
}))(Form.create({})(List));
